<?php
/*
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

/**
 * \file
 */
/// signifies an error with the submitted option
define("NAMEERR", 1);
/// signifies an error with the submitted request
define("REQUESTERR", 1 << 1);

////////////////////////////////////////////////////////////////////////////////
///
/// \fn remoteVCLCall($method, $args)
///
/// \param $method - method name 
/// \param $args - arguments to be passed to the method.
///
/// \brief makes a xmlrpc calls for given method with passed args.
///
////////////////////////////////////////////////////////////////////////////////
function remoteVCLCall($method, $args) {
        $request = xmlrpc_encode_request($method, $args);
        $header  = "Content-Type: text/xml\r\n";
        $header .= "X-User: admin\r\n";    // user your userid here
        $header .= "X-Pass: vcl2.2.1sandBox\r\n";  // user your password here
        $header .= "X-APIVERSION: 2";       // this is to allow for future changes to the api
        $context = stream_context_create(
                array(
                        'http' => array(
                                'method' => "POST",
                                'header' => $header,
                                'content' => $request
                        )
                )
        );
        //$file = file_get_contents("https://vcl.ncsu.edu/scheduling/index.php?mode=xmlrpccall", false, $context);
        //$file = file_get_contents("https://152.46.16.138/index.php?mode=xmlrpccall", false, $context);
	$cloudaddr = getCloudAddress();
//	print $cloudaddr;
        //print "cloud address", $cloudaddr;
        if ($cloudaddr === 'NULL') {
                print "Needs cloud address";
                exit;
        }
	$url = "https://{$cloudaddr}/index.php?mode=xmlrpccall";
//	$url = BASEURL . SCRIPT . "?mode=xmlrpccall";
//	print $url;
	$file = file_get_contents($url, false, $context);
//        print $file;
        $response = xmlrpc_decode($file);
        if(xmlrpc_is_fault($response)) {
                trigger_error("xmlrpc: {$response['faultString']} ({$response['faultCode']})");
                exit;
        }
        return $response;
}
////////////////////////////////////////////////////////////////////////////////
///
/// \fn getCloudAddress()
///
/// \brief returns the IPAddress of management node of VCL cloud
///
////////////////////////////////////////////////////////////////////////////////
function getCloudAddress()
{
	$result = mysql_query('select cloudip from ipaddress');
	if ($result) {
		$rc = mysql_result($result, 0);
		return $rc;
	}
	return 'NULL';
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn getInstanceCount()
///
/// \brief returns the count of computer resources that are in available state
///
////////////////////////////////////////////////////////////////////////////////
function getInstanceCount() {
        $result = mysql_query('select count(id) from computer where stateid=2');
        if ($result) {
                $rc = mysql_result($result, 0);
                return $rc;
        }
        return 0;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn getTypeID($type)
///
/// \param $type - resource type (computer/image/managementnode, schedule)
///
/// \return id from resourcetype table
///
/// \brief gets id field from resourcetype table for type
///
////////////////////////////////////////////////////////////////////////////////
function getTypeID($typename) {
        $type = mysql_real_escape_string($typename);
        $query = "SELECT id FROM resourcetype WHERE name = '$type'";
        $qh = doQuery($query, 101);
        if(mysql_num_rows($qh)) {
                $row = mysql_fetch_row($qh);
                return $row[0];
        }
        return NULL;
}

////////////////////////////////////////////////////////////////////////////////
///
/// \fn addNonLocalImage($data)
///
/// \param $data - an array with the following indexes:\n
/// name, prettyname, ownerid, platformid, OSid,
///
/// \brief adds a image to the image table
///
////////////////////////////////////////////////////////////////////////////////
function addNonLocalImage($data) {
	$ownerid = 1;
	$data['name'] = "vcl".$data['name'];
	$imgname = $data['name'];
	//if image with same name already exists just return imageid
	$select_query = "select id from image where prettyname LIKE '%$imgname%'";
        $iqh = doQuery($select_query, 101);
        if(mysql_num_rows($iqh)) {
                $row = mysql_fetch_row($iqh);
                return $row[0];
        }
	//get corresponding "vcl" OS id from OS table
	$osid = 1;
	$os_query = "select id from OS where type='vcl' LIMIT 1";
        $oqh = doQuery($os_query, 101);
        if(mysql_num_rows($oqh)) {
                $row = mysql_fetch_row($oqh);
                $osid = $row[0];
        } else {
                return NULL;
        }
	//insert image into image table
	$query = "INSERT INTO image "
	       .         "(name, "
	       .	 "prettyname, "
	       .         "ownerid, "
	       .         "platformid, "
	       .         "OSid) "
	       . "VALUES ('{$data["name"]}', "
	       .	 "'{$data["name"]}', "
	       .         "1, "
	       .         "1, "
	       .         "$osid)";
	doQuery($query, 205);

	// get last insert id
	$qh = doQuery("SELECT LAST_INSERT_ID() FROM image", 206);
	if(! $row = mysql_fetch_row($qh)) {
		abort(207);
	}
	$imageid = $row[0];
	// add entry in resource table
        $query = "INSERT INTO resource "
                         .        "(resourcetypeid, "
                         .        "subid) "
                         . "VALUES (13, "
                         .         "$imageid)";
        doQuery($query, 209);
        $qh = doQuery("SELECT LAST_INSERT_ID() FROM resource", 101);
        $row = mysql_fetch_row($qh);
        $resid = $row[0];
	//add image revision 
	$query = "INSERT INTO imagerevision "
               .        "(imageid, "
               .        "userid, "
               .        "datecreated, "
               .        "production, "
               .        "imagename) "
               . "VALUES ($imageid, "
               .        "1, "
               .        "NOW(), "
               .        "1, "
               .        "'{$data["name"]}') ";
        doQuery($query, 101);
	
	// add into resource group created
	$result = mysql_query("SELECT id FROM resourcegroup WHERE name = 'vcl_images'");
        if ($result) {
            $rc = mysql_result($result, 0);
			if ($rc) {
				$query = sprintf("INSERT INTO resourcegroupmembers(resourceid, resourcegroupid) VALUES(%d, %d)",$resid, $rc);
		                    doQuery($query, 101);
			}
        }
	//add reference of image added into vclResource table
	$query = sprintf("INSERT IGNORE INTO vclResources(resourceid, type) VALUES(%d, 13)",$imageid);
        doQuery($query, 101);
	//add image reference and image id mapping for other cloud
	
	$query = "INSERT IGNORE INTO vclImage(imageid, cloudimageid, type) VALUES($imageid, {$data["id"]}, '{$data["type"]}')";
	doQuery($query, 101);
	return $imageid;
}


////////////////////////////////////////////////////////////////////////////////
///
/// \fn addNonLocalComputer($data)
///
/// \param $data - an array with the following indexes:\n
/// ipaddress, stateid, platformid, scheduleid,
/// ram, numprocs, procspeed, network, hostname, type
///
/// \brief adds a computer to the computer table
///
////////////////////////////////////////////////////////////////////////////////
function addNonLocalComputer($count) {
	$notes = 'NULL';
	//retrieve provisioning id of vcl2vcl module
      	$result = mysql_query('select * from provisioning where name = "vcltovcl"');
	if ($result) {
		$rc = mysql_fetch_assoc($result);
		$provisioningid=$rc['id'];
	}
	else {
		$provisioningid=7;
	}
	//append vcl against hostnames of computers
	$hostname = "vclvm".$count;
	//check if already there is entry with the same hostname, if so just return
	$select_query = "select id from computer where hostname LIKE '%$hostname%'";
	$qh = doQuery($select_query, 101);
        if(mysql_num_rows($qh)) {
		$row = mysql_fetch_row($qh);
                return $row[0];
        }
	$query = "INSERT INTO computer "
               .        "(stateid, "
               .        "ownerid, "
               .        "platformid, "
               .        "scheduleid, "
               .        "currentimageid, "
               .        "RAM, "
               .        "procnumber, "
               .        "procspeed, "
               .        "network, "
               .        "hostname, "
               .        "type, "
               .        "notes, "
	       .	"location, "
               .        "provisioningid) "
               . "VALUES (2, "
               .         "1, "
               .         "1, "
               .         "1, "
               .         "4, "
               .         "1024, "
               .         "1, "
               .         "2000, "
               .         "1000, "
               .         "'$hostname', "
               .         "'blade', "
               .         "$notes, "
	       .	 "'vcl', "
               .         "$provisioningid)";
        doQuery($query, 195);
        $compid = dbLastInsertID();
	$query = "INSERT INTO resource "
                         .        "(resourcetypeid, "
                         .        "subid) "
                         . "VALUES (12, "
                         .         "$compid)";
        doQuery($query, 198);
        $resid = dbLastInsertID();
	//print "Resource added with resource ID: $resid<br>";    //Added by Chaitanya

        // add computer into vcl_computers resourcegroup id
	$result = mysql_query("SELECT id FROM resourcegroup WHERE name = 'vcl_computers'");
        if ($result) {
                $rc = mysql_result($result, 0);
                if ($rc) {
                        $query = sprintf("INSERT INTO resourcegroupmembers(resourceid, resourcegroupid) VALUES(%d, %d)",$resid, $rc);
                        doQuery($query, 101);
			//print "Resource group added\n";  //Added by Chaitanya
                }
        }
	//add reference of computer added into vclResource table
        $query = sprintf("INSERT INTO vclResources(resourceid, type) VALUES(%d, 12)",$compid);
        doQuery($query, 101);

	return $compid;
}

///////////////////////////////////////////////////////////////////////////////
///
/// \fn verifyUserRequest()
///
/// \brief verifies admin input if cloud can broker required no.of resources or not
///
////////////////////////////////////////////////////////////////////////////////
function verifyUserRequest($request)
{
        $rc = remoteVCLCall('XMLRPCgetInstanceCount', array());
//        print_r($rc);
        $count = $rc['count'];
        if ($count < $request) {
                trigger_error( "Not enough computers on cloud, it has got only $count computers available");
                return 0;
        }
        return $count;
}
///////////////////////////////////////////////////////////////////////////////
///
/// \fn getImageOsType()
///
/// \param $name - name of the image.
///
/// \brief returns the OS type of image.
///
////////////////////////////////////////////////////////////////////////////////
function getImageOsType($name) {
	$query = "select type from OS where id in (select OSid from image where prettyname LIKE '%$name%') LIMIT 1";	
	$result = mysql_query($query);
        if ($result) {
                $rc = mysql_result($result, 0);
                return $rc;
        }
	return 'Unknown type';
}
///////////////////////////////////////////////////////////////////////////////
///
/// \fn extendBrokerVCLRequest()
///
/// \param $reqid - request id for which reservation extend request is received
/// \param $duration - length of extension in minutes
///
/// \brief returns status of extension. if -1, request is still not registered with other cloud; if 1 request is failed on cloud; if 0 sucess
///
////////////////////////////////////////////////////////////////////////////////
function extendBrokerVCLRequest($reqid, $duration) {
	//determine if this request is for brokered image
	$query = "SELECT name FROM image WHERE id=(SELECT imageid FROM reservation WHERE requestid=$reqid)";
	$qh = doQuery($query, 146);
	if(! $row = mysql_fetch_row($qh)) {
                abort(148);
        }
	$name = $row[0];
	$vcl = "vcl";
	if (preg_match("/$vcl/i", $name)) {
		//check if this request is in vclinstances table
		$query = "SELECT id, rpcid FROM vclinstances WHERE requestid = $reqid";
		$qh = doQuery($query, 146);
		if(! $row = mysql_fetch_row($qh)) {
			return -1;
		}
		$id = $row[0];
		$rpcid = $row[1];
		$rc = remoteVCLCall('XMLRPCextendRequest', array($rpcid, $duration));
		if ($rc['status'] == 'error') {
		    print  $rc['errormsg'];
		    return 1;
		} else {
			return;
		}
	}
	else {
		return 0;
	}	
}
///////////////////////////////////////////////////////////////////////////////
///
/// \fn releaseBrokerVCLResources()
///
///
/// \brief releases the resources brokered.
///
////////////////////////////////////////////////////////////////////////////////
function releaseBrokerResources() {
	//delete corresponding computerid rows from reservation table and request table
	$request_query = "DELETE FROM request WHERE id IN (select requestid from reservation where computerid IN (select resourceid from vclResources where type=12))";
	$request_res = mysql_query($request_query);
	$reservation_query = "DELETE FROM reservation WHERE computerid IN (select resourceid from vclResources where type=12)";
	$reservation_res = mysql_query($reservation_query);
	//delete from vclComputer table
        $vclcomputer_query = "DELETE FROM vclComputer WHERE computerid IN (select resourceid from vclResources where type=12)";
        $vclcmp_res = mysql_query($vclcomputer_query);
	//delete rows added into computer/images table
	$comp_query = "DELETE FROM computer WHERE id IN (select resourceid from vclResources where type=12)";
	$comp_res = mysql_query($comp_query);
	if ($comp_res){
		$res = mysql_query("DELETE FROM vclResources where type=12");
	}
	//doQuery($comp_query, 153);
	//delete from vclImage table
	$vclimage_query = "DELETE FROM vclImage WHERE imageid IN (select resourceid from vclResources where type=13)";
	$vclimg_res = mysql_query($vclimage_query);
	//delete from log table
	$log_query = "DELETE FROM log WHERE imageid IN (select resourceid from vclResources where type=13)";
	$log_res = mysql_query($log_query);
	//delete from image revision
	$revision_query = "DELETE FROM imagerevision WHERE imageid IN (select resourceid from vclResources where type=13)";
        $revision_res = mysql_query($revision_query);
	//delete from image table
	$image_query = "DELETE FROM image WHERE id IN (select resourceid from vclResources where type=13)";
	$img_res = mysql_query($image_query);
	if ($img_res) {
		$res = mysql_query("DELETE FROM vclResources where type=13");
	}
	print "Released resources successfully\n";	
	//doQuery($image_query, 153);
}

?>

